<?php

namespace app\api\service;

use app\model\Activity;
use app\model\Money;
use app\model\PayRecord;
use app\model\ThirdVideos;
use app\model\User;
use app\model\WatchAdRecord;
use think\cache\driver\Redis;
use think\facade\Cache;
use app\common\Common;
use app\model\Banner;
use app\model\Videos;
use app\model\VideoTypes;
use app\model\VideoDetails;
use app\model\UserLove;
use app\model\WatchPayRecord;
use app\model\BingeWatch;
use app\model\Concern;
use app\model\Admin;
use app\model\VideoPayConfig;
use app\model\SetFollowDrama;
use app\model\OfficialAccounts;
use app\model\Records;
use app\common\Error;
use app\model\Applet;
use app\model\Link;
use app\model\MountedAppletCustomRechargeConfig;
use app\model\CustomRechargeTemplate;
use app\model\ResponsibilityPerson;
use app\model\Company;
use app\model\VideoTemplate;
/**
 * 首页服务类
 */
class HomeService
{
    private $bannerModel;
    private $videosModel;
    private $videoTypesModel;
    private $videoDetailsModel;
    private $userLoveModel;
    private $watchPayRecordModel;
    private $bingeWatchModel;
    private $concernModel;
    private $adminModel;
    private $videoPayConfigModel;
    private $setFollowDramaModel;
    private $officialAccountsModel;
    private $recordsModel;
    private $linkModel;
    private $payRecordModel;
    private $applet;
    private $mountedAppletCustomRechargeConfigModel;
    private $customRechargeTemplateModel;
    private $videoTemplateModel;
    private $responsibilityPersonModel;
    private $companyModel;
    private $userModel;
    /**
     * @var Redis
     */
    private $redis;

    public function __construct(
        Banner $bannerModel,
        Videos $videosModel,
        VideoTypes $videoTypesModel,
        VideoDetails $videoDetailsModel,
        UserLove $userLoveModel,
        WatchPayRecord $watchPayRecordModel,
        BingeWatch $bingeWatchModel,
        Concern $concernModel,
        Admin $adminModel,
        VideoPayConfig $videoPayConfigModel,
        SetFollowDrama $setFollowDramaModel,
        OfficialAccounts $officialAccountsModel,
        Records $recordsModel,
        Link $linkModel,
        PayRecord $payRecordModel,
        Applet $applet,
        MountedAppletCustomRechargeConfig $mountedAppletCustomRechargeConfigModel,
        CustomRechargeTemplate $customRechargeTemplateModel,
        VideoTemplate $videoTemplateModel,
        ResponsibilityPerson $responsibilityPersonModel,
        Company $companyModel,
        User $userModel
    )
    {
        $this->bannerModel = $bannerModel;
        $this->videosModel = $videosModel;
        $this->videoTypesModel = $videoTypesModel;
        $this->videoDetailsModel = $videoDetailsModel;
        $this->userLoveModel = $userLoveModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->bingeWatchModel = $bingeWatchModel;
        $this->concernModel = $concernModel;
        $this->adminModel = $adminModel;
        $this->videoPayConfigModel = $videoPayConfigModel;
        $this->setFollowDramaModel = $setFollowDramaModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->recordsModel = $recordsModel;
        $this->linkModel = $linkModel;
        $this->payRecordModel = $payRecordModel;
        $this->applet = $applet;
        $this->mountedAppletCustomRechargeConfigModel = $mountedAppletCustomRechargeConfigModel;
        $this->redis = Cache::store('redis')->handler();
        $this->customRechargeTemplateModel = $customRechargeTemplateModel;
        $this->videoTemplateModel = $videoTemplateModel;
	  $this->responsibilityPersonModel=$responsibilityPersonModel;
        $this->companyModel=$companyModel;
        $this->userModel = $userModel;
    }

    /**
     * 获取首页Banner列表
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param array params
     * @return array
     */
    public function getHomeBannerList($uid,$params=[])
    {
        $appId = $params['app_id'] ?? 1;;
        $redis = Cache::store('redis')->handler();
        $key = sprintf('%s-%s', config('redis_key.banner_diagram_key') , $appId);
        $redis->select(7);
        $data = $redis->get($key);

        $appletData = $this->applet->getInfoByWhere(['app_id' => $appId] , 'id');

        $appletId = 0;
        if(!empty($appletData)){
          $appletId = $appletData['id'];
        }

        if (empty($data)) {
            $data = $this->bannerModel->selectByAppletIdList(['video_id', 'cover_img','path','type', 'activity_id'], $appletId);
            $redis->set($key, json_encode($data), 600);
        } else {
            $data = json_decode($data, true);
        }

        $result = [];
        if ($data) {
            $videoIds = array_column($data, 'video_id');
            $playPlatform = $params['play_platform'] ?? 1;

            $redisKey = config('redis_key.banner_video_key');

            if($playPlatform == 1) { // 缓存键微信
                $redisKey = config('redis_key.banner_video_key');
            }elseif($playPlatform==2){ // 缓存抖音.
                $redisKey = config('redis_key.tiktok_banner_video_key');
            }

            $videoData = $redis->get($redisKey);

            if (empty($videoData)) {
                //$videoData = $this->videosModel->getDataByWhere(['id' => $videoIds, 'is_delete' => 0, 'is_shelves' => 1], 'id, name');
                // by huangxiaoshan update 2023-07-24 新增支持按播放平台过滤进行过滤.

                $where = [];
                //新加一个判断是否为广告链接进入，如果是就不限制，不是就限制
                //新加 start
                $linkidstatus=$redis->get('link_id_status'.$uid.'-'.$appId);
                if(empty($linkidstatus)||$linkidstatus==0){
                    $app=$this->applet->getInfoById($appId,'vt_id');
                    if(!empty($app['vt_id'])) {
                        $vtempte = $this->videoTemplateModel->getInfoById($app['vt_id'], '*');
                        if(!empty($vtempte['video_arr'])) {
                            $where[] = ['id','', $vtempte['video_arr']];
                        }
                    }
                }
                //新加 end 
                $where[] = ['play_platform','find in set',$playPlatform];
                $where[] = ['id','in',$videoIds];
                $where[] = ['is_delete','=',0];
                $where[] = ['is_shelves','=',1];
                $videoData = $this->videosModel->getDataByWhere($where, 'id, name, drama_id');
                // end
                $redis->set($redisKey, json_encode($videoData), 86400);
            } else {
                $videoData = json_decode($videoData, true);
            }

            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $videoDetailIds = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($videoDetailIds), config('redis_key.user_watch_record_expire'));
            }

            $videoList = array_column($videoData, 'name', 'id');
            $videoList2 = array_column($videoData, 'drama_id', 'id');

            foreach ($data as $key => $item) {
                if($item['activity_id'] > 0 && empty($item['activity'])){
                    continue;
                }
                if (!empty($videoList[$item['video_id']])) {
                    $result[] = [
                        'id' => $item['video_id'],
                        'name' => $videoList[$item['video_id']],
                        'video_id' => $item['video_id'],
                        'cover_img' => $item['cover_img'],
                        'path' => $item['path'],
                        'video_detail_id' => empty($videoDetailIds[$item['video_id']]) ? 0 : $videoDetailIds[$item['video_id']],
                        'type' => $item['type'] ?? '',
                        'activity_id' => $item['activity_id'] ?? 0,
                        'drama_id' => $videoList2[$item['video_id']] ?? '',
                    ];
                }else{
                    $activity = Activity::getInfoById($item['activity_id']);
                    $result[] = [
                        'id' => $item['activity_id'],
                        'name' => $activity ? $activity->name : '',
                        'video_id' => 0,
                        'cover_img' => $item['cover_img'],
                        'path' => $item['path'],
                        'video_detail_id' => 0,
                        'type' => $item['type'] ?? '',
                        'activity_id' => $item['activity_id'] ?? 0,
                    ];
                }
            }
        }

        return $result;
    }

    /**
     * 获取推荐数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @return array
    */
    public function getRecommendedList($params, $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;

        $field = 'id, name, cover_img, is_free, label, title_label,original_id,sylloge,drama_id';
        // 增加判断当前链接是否属于分销商
        $is_automatic = $this->getIsAutomatic($uid);
        $redis = Cache::store('redis')->handler();
        $appId = $params['app_id'] ?? 1;

        if (!empty($params['is_filings'])) {
            // 抖音小程序返回备案剧
            $key = config('redis_key.api_home_video_recommend_list').$is_automatic.$page.'-douyin-applet'.$appId;
        } else {
            $key = config('redis_key.api_home_video_recommend_list').$is_automatic.$page.$appId;
        }

        $redis->select(7);
        $data = $redis->get($key);

        if (empty($data)) {
            // by huangxiaoshan update 2023-07-24 新增按播放平台进行数据过滤.
            $play_platform = $params['play_platform'] ?? 1;
            //$where = ['is_recommended' => 1, 'is_delete' => 0, 'is_shelves' => 1];
            $where = [];
            //新加一个判断是否为广告链接进入，如果是就不限制，不是就限制
            //新加 start
            $linkidstatus=$redis->get('link_id_status'.$uid.'-'.$appId);
            if(empty($linkidstatus)||$linkidstatus==0){
                $app=$this->applet->getInfoById($appId,'vt_id');
                if(!empty($app['vt_id'])) {
                    $vtempte = $this->videoTemplateModel->getInfoById($app['vt_id'], '*');
                    if(!empty($vtempte['video_arr'])) {
                        $where[] = ['id','', $vtempte['video_arr']];
                    }
                }
            }
            //新加 end 
            $where[] = ['play_platform','find in set',$play_platform];
            $where[] = ['is_recommended','=',1];
            $where[] = ['is_delete','=',0];
            $where[] = ['is_shelves','=',1];
            //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
            //自投appid,展示自投剧
        
           //增加一个判断当前链接是否是分销商
            if(!empty($params['is_filings'])){
                $where[] = ['is_copy','=',0];
            }elseif($is_automatic != 2){
                $where[] = ['is_copy','=',(int)$is_automatic];
            }else{
                if(in_array($appId, config('enum.my_appid'))){
                    $where[] = ['is_copy','=',0];
                }else{
                    $where[] = ['is_copy','=',1];
                }
            }
            //end
            // 是否是备案剧 is_filings = 1，且抖小展示原始备案剧（根据产品需求）
            if (!empty($params['is_filings'])) {
                //$where['is_filings'] = 1;
                $where[] = ['is_filings','=',1];
            }
            $data = $this->videosModel->getRecommendedData($where, $field, $page, $limit);
            //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
            //不是自投appid,展示复制剧
            if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1){
                foreach($data['data'] as $k_d =>$v_d){
                    $original = $this->videosModel->getInfoById($data['data'][$k_d]['original_id']); 
                    if(!empty($original)){
                        $data['data'][$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                    }
                }
            }
            // end
            $redis->set($key, json_encode($data), 86400);
        } else {
            $data = json_decode($data, true);
        }

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');
            // $watchData = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_detail_id, video_id');
            // $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $videoDetailIds = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($videoDetailIds), config('redis_key.user_watch_record_expire'));
            }

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['video_detail_id'] = empty($videoDetailIds[$item['id']]) ? 0 : $videoDetailIds[$item['id']];
            }
        }

        return $data;
    }

    /**
     * 获取分类数据
    */
    public function getTypeData()
    {
        // 
        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api_home_video_type_data');
        $redis->select(7);
        $data = $redis->get($key);

        if (empty($data)) {
            $data = $this->videoTypesModel->getUsedTypeData();
            $redis->set($key, json_encode($data), 86400);
        } else {
            $data = json_decode($data, true);
        }
        return $data;
    }

    //自定义短剧类型
    public function getCustomVideoTypes($app_id)
    {
        $types = [];
        $applet = $app_id ? $this->applet->getInfoByWhere(['app_id' => $app_id], 'is_open_ad') : [];
        $isOpenAd = $applet ? $applet['is_open_ad'] : 0;
        if ($isOpenAd) {
            $types[] = [
                'key' => 4,
                'value' => '免费'
            ];
        }
        return $types;
    }

    /**
     * 获取分类id获取数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param string fields
     * @param string order
     * @return array
    */
    public function getListByTypeId(array $params, $uid)
    {
        $videoTypeId = is_numeric($params['type_id'])?$params['type_id']:0;
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;
        $fields = 'id, video_type_id, name, cover_img, label, title_label,original_id';
        $appId = $params['app_id'] ?? 1;

        $playPlatform = $params['play_platform'] ?? 1;
        //增加判断当前链接是否属于分销商
        $is_automatic= $this->getIsAutomatic($uid);
        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api_get_type_video_by_id').$videoTypeId.'-'.$page.$appId;
        if($playPlatform == 1){ // 微信小程序键
            $key = config('redis_key.api_get_type_video_by_id').$videoTypeId.'-'.$page.$appId;
        }else if($playPlatform == 2){ // 抖音键
            $key = config('redis_key.tiktok_api_get_type_video_by_id').$videoTypeId.'-'.$page.$appId;
        }

        $redis->select(7);
            
        $data = $redis->get($key);

        if (empty($data)) {
            // by huangxiaoshan update 2023-07-24 新增功能,按播放平台过滤

            $where = [];
            //新加一个判断是否为广告链接进入，如果是就不限制，不是就限制
            //新加 start
            $linkidstatus=$redis->get('link_id_status'.$uid.'-'.$appId);
            if(empty($linkidstatus)||$linkidstatus==0){
                $app=$this->applet->getInfoById($appId,'vt_id');
                if(!empty($app['vt_id'])) {
                    $vtempte = $this->videoTemplateModel->getInfoById($app['vt_id'], '*');
                    if(!empty($vtempte['video_arr'])) {
                        $where[] = ['id','', $vtempte['video_arr']];
                    }
                }
            }
            //新加 end 
            $where[] = ['play_platform','find in set',$playPlatform];
            $where[] = ['is_delete','=',0];
            $where[] = ['is_shelves','=',1];
            $where[] = ['video_type_id','=',$videoTypeId];
            //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
            //自投appid,展示自投剧
            //增加一个判断当前链接是否是分销商
            if($is_automatic != 2){
                $where[] = ['is_copy','=',(int)$is_automatic];
            }else{
                if(in_array($appId, config('enum.my_appid'))){
                    $where[] = ['is_copy','=',0];
                }else{
                    $where[] = ['is_copy','=',1];
                }
            }
            //end
            //$data = $this->videosModel->getDataByVideoTypeId($videoTypeId, $page, $limit, $fields);
            // 新接口需要进行平台的过滤。
            $data = $this->videosModel->getDataByVideoTypeIdNew($where, $page, $limit, $fields);
            //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
            //不是自投appid,展示复制剧
            if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1){
                foreach($data['data'] as $k_d =>$v_d){
                    $original = $this->videosModel->getInfoById($data['data'][$k_d]['original_id']); 
                    if(!empty($original)){
                        $data['data'][$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                    }
                }
            }
            //end
            $redis->set($key, json_encode($data), 21600);
        } else {
            $data = json_decode($data, true);
        }

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');
            // $watchData = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_detail_id, video_id');
            // $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $videoDetailIds = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($videoDetailIds), config('redis_key.user_watch_record_expire'));
            }

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['video_detail_id'] = empty($videoDetailIds[$item['id']]) ? 0 : $videoDetailIds[$item['id']];
            }
        }
        return $data;
    }

    /**
     * 获取用户信息
     * @param $uid
     * @return mixed
     */
    private function getUserInfo($uid)
    {
        $key = config('redis_key.api.user_login') . $uid;
        $userInfo = $this->redis->get($key);
        return json_decode($userInfo, true);
    }

    /**
     * 获取所有视频
     * @param $videoId
     * @return array|mixed
     */
    private function getVideoAllDetail($videoId,$playFlatform=1,$originalId = 0)
    {
        if ($playFlatform == 1) { // 微信键
            $key = config('redis_key.get_all_video_data_by_video_id') . $videoId;
        } elseif($playFlatform == 2) { // 抖音键.
            $key = config('redis_key.get_tiktok_video_data_by_video_id') . $videoId;
        } elseif($playFlatform == 3 ){ // 快手键
            $key = config('redis_key.get_kwai_video_data_by_video_id') . $videoId;
        }

      
        $allVideoData = $this->redis->get($key);
        if ($allVideoData) {
            $allVideoData= json_decode($allVideoData, true);
        }else{
            // by huangxiaoshan update 根据不一样的 平台返回不一样的播放地址(默认是腾讯的也就是腾讯小程序的播放地址。)
            $fields = 'id, video_id, is_pay, pay_amount, give_count, url, sort, share_count, is_members';

            if ($playFlatform == 1) {
                // 腾讯
                $fields = 'id, video_id, is_pay, pay_amount, give_count, url, sort, share_count, is_members';
            } else if ($playFlatform == 2) {
                // 抖音
                $fields = 'id, video_id, is_pay, pay_amount, give_count, ifnull(hls_url , third_url) as url, sort, share_count, is_members, platform_config';
            }
            // end.

            $allVideoData = $this->videoDetailsModel->getAllDataByVideoId($videoId, $fields);
            if ($playFlatform == 2) {
                $video_id = $originalId ?: $videoId;
                $thirdVideo = ThirdVideos::getOneByWhere(['video_id' => $video_id, 'platform' => 2],'id,album_id,is_authorize');
                if ($thirdVideo && !empty($thirdVideo['album_id'])) {
                    if ($originalId) {
                        $originalAllVideoData = $this->videoDetailsModel->getAllDataByVideoId($originalId, 'sort, platform_config');
                        $data = $originalAllVideoData;
                    } else {
                        $data = $allVideoData;
                    }
                    $sortData = [];
                    foreach ($data as $item) {
                        $platformConf = $item['platform_config']['douyinyun'] ?? [];
                        if (!$platformConf || empty($platformConf['episode_id'])) continue;
                        $sortData[$item['sort']] = (string)$platformConf['episode_id'];
                    }
                    foreach ($allVideoData as $k => $datum) {
                        $allVideoData[$k]['platform_config'] = [
                            'album_id' => $thirdVideo['album_id'],
                            'episode_id' => $sortData[$datum['sort']] ?? ''
                        ];
                        $allVideoData[$k]['url'] = '';
                    }
                } else {
                    foreach ($allVideoData as $k => $datum) {
                        $allVideoData[$k]['platform_config'] = [
                            'album_id' => '',
                            'episode_id' => ''
                        ];
                    }
                }
            }
            $this->redis->select(7);
            $this->redis->set($key, json_encode($allVideoData), 7200);
        }
        if($playFlatform==1||$playFlatform==3){
            $this->redis->select(5);
            $drama_id=$this->videosModel->getInfoById($videoId,'drama_id');
            $video_json=$this->redis->get('openweixin_drama_data:'.$drama_id['drama_id']);
            if(!empty($video_json)){
                $video_arr=json_decode($video_json,true);
                $arr=$video_arr['data'];
                foreach($allVideoData as $key =>$val){
                    if(!empty($arr[$val['sort']])){
                        $allVideoData[$key]['url']=$arr[$val['sort']]['hls_url'];
                    }
                }
            }
        }
        return $allVideoData;
    }

    /**
     * 获取video数据
     * @param $videoId
     * @return array|mixed
     */
    private function getVideoInfo($videoId)
    {
        $key = config('redis_key.get_video_data_by_video_id') . $videoId;
        $videoData = $this->redis->get($key);
        if ($videoData) {
            return json_decode($videoData, true);
        }

        $videoData = $this->videosModel->getInfoById($videoId, 'id, uid, cover_img, name, synopsis, is_shelves, is_delete, update_sort, status, original_id,type');
        $this->redis->set($key, json_encode($videoData), 7200);

        return $videoData;
    }

    /**
     * 获取用户视频消费记录
     * 
     * @param $videoId
     * @param $uid
     * @return array
     */
    private function getVideoPayLog($videoId, $uid)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(4);
        $key = config('redis_key.video_watch_record').$uid.'-'.$videoId;

        // 优先从redis获取
        if ($redisWatchRecordData = $redis->get($key)) {
            $videoDetailIds = json_decode($redisWatchRecordData, true);
        } else {
            // 否则从数据库获取
            $payData = $this->watchPayRecordModel->getInfo(['video_id' => $videoId, 'uid' => $uid], 'id, video_detail_id');
            $videoDetailIds = array_column($payData, 'video_detail_id');

            $redis->set($key, json_encode($videoDetailIds), config('redis_key.video_watch_record_expire'));
        }

        return $videoDetailIds;
    }

    /**
     * 获取admin 信息
     * @param $uid
     * @return array|mixed
     */
    private function getAdminInfo($uid)
    {
        $key = config('redis_key.admin_user_data_uid') . $uid;
        $info = $this->redis->get($key);
        if ($info) {
            return json_decode($info, true);
        }

        $adminUserData = $this->adminModel->getInfoById($uid, 'id, profile_photo');
        $this->redis->set($key, json_encode($adminUserData), 86400);

        return $adminUserData;
    }

    /**
     * 获取视频详情
     * @param array params
     * @param int video_id
     * @param int video_detail_id
     * @param int uid
     * @return array
     */
    public function getVideoDetail($params, $uid)
    {
        $data = [];
        // by huangxiaoshan update 2023-07-25 新增支持按播放平台过滤进行过滤.
        $playPlatform = $params['play_platform'] ?? 1;
        $app_id = $params['app_id'] ?? '';

        $videoId = $params['video_id'];
        $detailId = isset($params['video_detail_id']) ? $params['video_detail_id'] : 0;
        $userInfo = $this->getUserInfo(intval($uid));

        $this->redis->select(7);

        // 获取video数据
        $videoData = $this->getVideoInfo($videoId);
        if (!empty($videoData['is_delete']) || empty($videoData['is_shelves'])) {
            return ['code' => Error::THE_SHORT_PLAY_OFF_SHELF_CODE, 'message' => Error::THE_SHORT_PLAY_OFF_SHELF];
        }

        $data['cover'] = $videoData['cover_img'];
        $data['video_name'] = $videoData['name'];
        $data['synopsis'] = $videoData['synopsis'];
        $data['update_sort'] = $videoData['update_sort'];
        $data['status'] = $videoData['status'];
        $data['video_type'] = 0;
        $data['ad_id'] = '';
        if (!isset($videoData['original_id'])) {
            $videoData['original_id'] = 0;
        }

        // 是否追剧
        $bingeWatchData = $this->bingeWatchModel->getInfo(['uid' => $uid, 'video_id' => $videoId], 'id');
        $data['chase'] = empty($bingeWatchData) ? false : true;

        // 是否关注该用户
        $concernData = $this->concernModel->getInfo(['admin_id' => $videoData['uid'], 'uid' => $uid]);
        $data['admin']['concern'] = empty($concernData) ? false : true;

        $adminInfo = $this->getAdminInfo($videoData['uid']);
        $data['admin']['cover'] = $adminInfo['profile_photo'] ?? '';
        $data['admin']['admin_id'] = $adminInfo['id'] ?? '';

        if (!empty($app_id) && isset($videoData['type']) && $videoData['type'] == 3) {
            $appletData = $this->applet->getInfoByWhere(['app_id' => $app_id] , 'id,is_open_ad,ad_id');
            $is_open_ad = $appletData ? $appletData['is_open_ad'] : 0;
            if ($is_open_ad > 0) {
                $data['video_type'] = 1;
                $data['ad_id'] = Applet::getAdIdByScene($appletData, Applet::AD_SCENE_1);
                list($data['collect'], $data['video']) = $this->getFreeVideoDetail($uid, $videoId, $playPlatform, $videoData['original_id'], $detailId);
                return $data;
            }
        }

        $customChargeConfigureData = [];
        if (!empty($userInfo['link_id'])) {

            // 获取链接数据
            $linkData = $this->linkModel->getInfoByWhere(['id' => $userInfo['link_id'], 'video_id' => $videoId], 'video_pay_setting_id, is_new_recharge_setting, recharge_template_id');

            if (!empty($linkData) && $linkData['is_new_recharge_setting'] == 2) {
                if (!empty($linkData['recharge_template_id'])) {
                    $customChargeConfigureData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $linkData['recharge_template_id'], 'video_id' => $videoId], 'sort, charge_type, pay_amount, interval_recharge');
                    if (!empty($customChargeConfigureData) && $customChargeConfigureData['charge_type'] == 2) {
                        $customChargeData = json_decode($customChargeConfigureData['interval_recharge'], true);
                    }
                }
            } else if (!empty($linkData) && $linkData['is_new_recharge_setting'] == 1) {
                // 获取自定义的短剧收费配置
                $customChargeConfigureData = $this->videoPayConfigModel->getInfoByWhere(['id' => $linkData['video_pay_setting_id']], 'sort, status, pay_amount');
            }

        } else {
            // 判断是否是挂载的小程序 获取自定义收费设置
            $this->redis->select(8);
            $mountKey = config('redis_key.api.user_login_mount_key').$uid;
            $mountPlatform = $this->redis->get($mountKey);
            if ($mountPlatform == 1) {
                $mountCustomChargeConfigureData = $this->mountedAppletCustomRechargeConfigModel->getInfoByWhere(['platform' => 1, 'video_id' => $videoId], 'sort, pay_amount, is_new_version, recharge_template_id');
                if (!empty($mountCustomChargeConfigureData) && !empty($mountCustomChargeConfigureData['is_new_version'])) {

                    // 新版收费
                    $isNewVersion = $mountCustomChargeConfigureData['is_new_version'];

                    $mountCustomChargeConfigureData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $mountCustomChargeConfigureData['recharge_template_id'], 'video_id' => $videoId], 'sort, charge_type, pay_amount, interval_recharge');
                    if ($mountCustomChargeConfigureData) {
                        $mountCustomChargeConfigureData['is_new_version'] = $isNewVersion;
                        if (!empty($mountCustomChargeConfigureData) && $mountCustomChargeConfigureData['charge_type'] == 2) {
                            $customChargeData = json_decode($mountCustomChargeConfigureData['interval_recharge'], true);
                        }
                    }
                    
                }
            } else if ($mountPlatform == 2) {
                $mountCustomChargeConfigureData = $this->mountedAppletCustomRechargeConfigModel->getInfoByWhere(['platform' => 2, 'video_id' => $videoId], 'sort, pay_amount, is_new_version, recharge_template_id');
                if (!empty($mountCustomChargeConfigureData) && !empty($mountCustomChargeConfigureData['is_new_version'])) {
                    // 新版收费
                    $isNewVersion = $mountCustomChargeConfigureData['is_new_version'];

                    $mountCustomChargeConfigureData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $mountCustomChargeConfigureData['recharge_template_id'], 'video_id' => $videoId], 'sort, charge_type, pay_amount, interval_recharge');
                    if ($mountCustomChargeConfigureData) {
                        $mountCustomChargeConfigureData['is_new_version'] = $isNewVersion;
                        if ($mountCustomChargeConfigureData && $mountCustomChargeConfigureData['charge_type'] == 2) {
                            $customChargeData = json_decode($mountCustomChargeConfigureData['interval_recharge'], true);
                        }
                    }
                }
            }
        }
        // 检查pay_record表该用户是否有对应此视频解锁全集类型的支付
        $unlockAll = $this->payRecordModel->getInfo(['uid' => $uid, 'type' => Money::TYPE_UNLOCK_ALL, 'video_id' => $videoId, 'status' => 1, ['refund_status', 'in', [PayRecord::REFUND_STATUS_DEFAULT,PayRecord::REFUND_STATUS_FAIL]]]);

        $videoDetailIds = $this->getVideoPayLog($videoId, $uid);
        $this->redis->select(7);

        // 是否关注
        $loveResult = $this->userLoveModel->getInfo(['uid' => $uid, 'video_id' => $videoId], 'id, video_detail_id');
        $isLoveData = array_column($loveResult, 'id', 'video_detail_id');

        //检查是否会员
        if ($playPlatform == 2) {
            $userData = $this->userModel->getInfoById($uid, 'id,is_members,expiration_time');
            $is_member = 0;
            if ($userData && $userData['is_members'] == 1 && $userData['expiration_time'] > time()) {
                $payRecords = $this->payRecordModel
                    ->field('id,order_no,type,video_id,total_fee,activation_time,pay_time,refund_status')
                    ->where(['uid' => $uid, 'status' => 1])
                    ->where('refund_status','<>', PayRecord::REFUND_STATUS_SUCC)
                    ->whereIn('type',[2,3,4,5,6,7,8,11,15])
                    ->select()->toArray();

                $is_free = app(VideoService::class)->memberMatchFree($payRecords, $videoId);
                $is_member = $is_free ? 1 : 0;
            }
            $data['is_member'] = $is_member;
        }

        $data['collect'] = $this->getVideoAllDetail($videoId,$playPlatform,$videoData['original_id']);// by huangxiaoshan update 2023-07-25
        $currentIndex = 0;
        foreach ($data['collect'] as $index => $videoDetail) {
             //2023-12-27增加一个参数，用户只判断剧集是否免费，不以用户是否购买为导向
             $data['collect'][$index]['is_free']=$data['collect'][$index]['is_pay'];
            if (!empty($customChargeConfigureData) && (($linkData['is_new_recharge_setting'] == 1) || ($linkData['is_new_recharge_setting'] == 2 && $customChargeConfigureData['charge_type'] == 1))) {
                $data['collect'][$index]['is_pay'] = 1;
                $data['collect'][$index]['pay_amount'] = $customChargeConfigureData['pay_amount'];

                if ($customChargeConfigureData['sort'] > $videoDetail['sort']) {
                    $data['collect'][$index]['is_pay'] = 0;
                    $data['collect'][$index]['pay_amount'] = 0;
                    $data['collect'][$index]['is_free']=0;
                }
            } else if (!empty($customChargeConfigureData) && $linkData['is_new_recharge_setting'] == 2 && $customChargeConfigureData['charge_type'] == 2) {
                // 新版自定义收费（按区间收费）
                if ($customChargeData) {
                    foreach ($customChargeData as $value) {
                        if ($videoDetail['sort'] >= $value['start'] && $videoDetail['sort'] <= $value['end']) {
                            $data['collect'][$index]['is_pay'] = 1;
                            $data['collect'][$index]['pay_amount'] = $value['pay_amount'];
                        } else if ($videoDetail['sort'] > $value['end']) {
                            $data['collect'][$index]['is_pay'] = 1;
                            $data['collect'][$index]['pay_amount'] = $videoDetail['pay_amount'];
                        } else if ($videoDetail['sort'] < $customChargeData[0]['start']) {
                            $data['collect'][$index]['is_pay'] = 0;
                            $data['collect'][$index]['pay_amount'] = 0;
                            $data['collect'][$index]['is_free']=0;
                        }
                    }
                }
            } else if (!empty($mountCustomChargeConfigureData)) {
                // 挂载
                $data['collect'][$index]['is_pay'] = 1;
                $data['collect'][$index]['pay_amount'] = $mountCustomChargeConfigureData['pay_amount'];

                if (empty($mountCustomChargeConfigureData['is_new_version']) && $mountCustomChargeConfigureData['sort'] > $videoDetail['sort']) {
                    // 老版本挂载
                    $data['collect'][$index]['is_pay'] = 0;
                    $data['collect'][$index]['pay_amount'] = 0;
                    $data['collect'][$index]['is_free']=0;
                } else if (!empty($mountCustomChargeConfigureData['is_new_version']) && $mountCustomChargeConfigureData['charge_type'] == 1 && $mountCustomChargeConfigureData['sort'] > $videoDetail['sort']) {
                    // 新版本按固定K币
                    $data['collect'][$index]['is_pay'] = 0;
                    $data['collect'][$index]['pay_amount'] = 0;
                    $data['collect'][$index]['is_free']=0;
                } else if (!empty($mountCustomChargeConfigureData['is_new_version']) && $mountCustomChargeConfigureData['charge_type'] == 2) {
                    if ($customChargeData) {
                        foreach ($customChargeData as $value) {
                            if ($videoDetail['sort'] >= $value['start'] && $videoDetail['sort'] <= $value['end']) {
                                $data['collect'][$index]['is_pay'] = 1;
                                $data['collect'][$index]['pay_amount'] = $value['pay_amount'];
                            } else if ($videoDetail['sort'] > $value['end']) {
                                $data['collect'][$index]['is_pay'] = 1;
                                $data['collect'][$index]['pay_amount'] = $videoDetail['pay_amount'];
                            } else if ($videoDetail['sort'] < $customChargeData[0]['start']) {
                                $data['collect'][$index]['is_pay'] = 0;
                                $data['collect'][$index]['pay_amount'] = 0;
                                $data['collect'][$index]['is_free']=0;
                            }
                        }
                    }
                }

            }

            if (($data['collect'][$index]['is_pay'] == 1 && in_array($videoDetail['id'], $videoDetailIds)) || count($unlockAll) > 0) {
                $data['collect'][$index]['is_pay'] = 0;
                $data['collect'][$index]['pay_amount'] = 0;
            }

            if ($data['collect'][$index]['is_pay'] == 1 && isset($is_member) && $is_member == 1) {
                $data['collect'][$index]['is_pay'] = 0;
                $data['collect'][$index]['pay_amount'] = 0;
            }

            if ($detailId && $videoDetail['id'] == $detailId) {
                $currentIndex = $index;
            }

            $data['collect'][$index]['is_love'] = empty($isLoveData[$videoDetail['id']]) ? 0 : 1;
        }

        $data['video'] = $data['collect'][$currentIndex] ?? [];

        $data['video']['last'] = '';
        $data['video']['next'] = '';

        if (isset($data['collect'][$currentIndex - 1])) {
            $data['video']['last'] = $data['collect'][$currentIndex - 1]['id'];
        }

        if (isset($data['collect'][$currentIndex + 1])) {
            $data['video']['next'] = $data['collect'][$currentIndex + 1]['id'];
        }

        $data['video']['love'] = !empty($data['video']['id']) && !empty($isLoveData[$data['video']['id']]) ? true : false;
        return $data;
    }

    //免费专区详情
    private function getFreeVideoDetail($uid, $videoId, $playPlatform, $originalId, $detailId): array
    {
        $collects = $this->getVideoAllDetail($videoId, $playPlatform, $originalId);
        // 是否关注
        if (!is_null($detailId)) {
            $loveResult = $this->userLoveModel->getInfo(['uid' => $uid, 'video_id' => $videoId], 'id, video_detail_id');
            $isLoveData = array_column($loveResult, 'id', 'video_detail_id');
        } else {
            $isLoveData = [];
        }

        //检查是否会员
        $userInfo = $this->userModel->getInfoById($uid, 'id,is_members,expiration_time');
        $is_member = 0;
        if ($userInfo && $userInfo['is_members'] == 1 && $userInfo['expiration_time'] > time()) {
            $is_member = 1;
        }

        // 检查pay_record表该用户是否有对应此视频解锁全集类型的支付
        $unlockAll = $this->payRecordModel->getInfo(['uid' => $uid, 'type' => Money::TYPE_UNLOCK_ALL, 'video_id' => $videoId, 'status' => 1, ['refund_status', 'in', [PayRecord::REFUND_STATUS_DEFAULT,PayRecord::REFUND_STATUS_FAIL]]]);

        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        $records = WatchAdRecord::getByWhereAndLimit([
            'uid' => $uid,
            'video_id' => $videoId,
            ['created_at','between', [$start_time, $end_time]]
        ],'detail_id');

        $detailIds = $records ? array_column($records,'detail_id') : [];

        $currentIndex = 0;
        foreach ($collects as $index => &$collect) {
            $collect['is_love'] = empty($isLoveData[$collect['id']]) ? 0 : 1;
            $collect['is_free'] = $collect['is_pay'];
            $collect['pay_amount'] = 0;
            if ($detailId && $collect['id'] == $detailId) {
                $currentIndex = $index;
            }
            if (!$collect['is_pay']) {
                continue;
            }
            if ($is_member || in_array($collect['id'], $detailIds) || count($unlockAll) > 0) {
                $collect['is_pay'] = 0;
            }
        }
        $currentVideo = $collects[$currentIndex] ?? [];

        $currentVideo['last'] = isset($collects[$currentIndex - 1]) ? $collects[$currentIndex - 1]['id'] : '';
        $currentVideo['next'] = isset($collects[$currentIndex + 1]) ? $collects[$currentIndex + 1]['id'] : '';
        $currentVideo['love'] = !empty($currentVideo['is_love']);

        return [$collects, $currentVideo];
    }

    //获取短剧数据
    public function getDramaDetail($params)
    {
        //$playPlatform = $params['play_platform'] ?? 1;
        //$app_id = $params['app_id'] ?? '';
        $videoId = $params['video_id'];
        $videoData = $this->videosModel->getInfoById(
            $videoId,
            'id,name,synopsis,is_shelves,is_delete,status,original_id,type,sylloge,is_money,drama_id'
        );
        if (!empty($videoData['is_delete']) || empty($videoData['is_shelves'])) {
            return [
                'code' => Error::THE_SHORT_PLAY_OFF_SHELF_CODE,
                'message' => (!empty($videoData['name']) ? '《'. $videoData['name'] . '》' : '该短剧') .'已下架'
            ];
        }
        return $videoData;
    }

    //微信新版视频详情
    public function wechatVideoDetail($params, $uid)
    {
        $playPlatform = $params['play_platform'] ?? 1;
        $app_id = $params['app_id'] ?? '';
        $videoId = $params['video_id'];
        //$detailId = isset($params['video_detail_id']) ? $params['video_detail_id'] : 0;
        $userInfo = $this->getUserInfo(intval($uid));

        // 获取video数据
        $videoData = $this->videosModel->getInfoById(
            $videoId,
            'id,uid,name,synopsis,is_shelves,is_delete,update_sort,status,original_id,type,sylloge,is_money,drama_id'
        );
        if (!empty($videoData['is_delete']) || empty($videoData['is_shelves'])) {
            return ['code' => Error::THE_SHORT_PLAY_OFF_SHELF_CODE, 'message' => Error::THE_SHORT_PLAY_OFF_SHELF];
        }

        $data = [
            'video_name' => $videoData['name'],
            'synopsis' => $videoData['synopsis'],
            'update_sort' => $videoData['update_sort'],
            'status' => $videoData['status'],
            'drama_id' => $videoData['drama_id'],
            'src_appid' => 'wx9e795df72358378b',
            'video_type' => 0,
            'ad_id' => ''
        ];

        //广告接入
        /*if (!empty($app_id) && isset($videoData['type']) && $videoData['type'] == 3) {
            $appletData = $this->applet->getInfoByWhere(['app_id' => $app_id] , 'id,is_open_ad,ad_id');
            $is_open_ad = $appletData ? $appletData['is_open_ad'] : 0;
            if ($is_open_ad > 0) {
                $data['video_type'] = 1;
                $data['ad_id'] = Applet::getAdIdByScene($appletData, Applet::AD_SCENE_1);
                list($data['collect'], $_) = $this->getFreeVideoDetail($uid, $videoId, $playPlatform, $videoData['original_id'], null);
                //加密数据
                $encryptData = $this->wechatEncryptData($data['collect'], $uid, $videoData['drama_id']);
                if ($encryptData) {
                    $data['free_list'] = $encryptData['freeList'];
                    $data['encryptStr'] = $encryptData['encrypt'];
                }
                return $data;
            }
        }*/

        /** @var $customChargeService CustomChargeService */
        $customChargeService = app(CustomChargeService::class);

        // 判断是否是挂载的小程序 获取自定义收费设置
        $this->redis->select(8);
        $mountKey = config('redis_key.api.user_login_mount_key').$uid;
        $mountPlatform = $this->redis->get($mountKey);

        $tempConf = '';
        if ($mountPlatform) {   //优先挂载判断
            $tempConf = 'mount';
            list($mountFixedChargeData, $intervalChargeData) = $customChargeService->getMountConfigure($mountPlatform, $videoId);

        } elseif (!empty($userInfo['link_id'])) {
            $tempConf = 'link';
            list($fixedChargeData, $intervalChargeData, $newRechargeConf) = $customChargeService->getLinkConfigure($userInfo['link_id'], $videoId);
        }

        // 检查pay_record表该用户是否有对应此视频解锁全集类型的支付
        $unlockAll = $this->payRecordModel->getInfo([
            'uid' => $uid,
            'type' => Money::TYPE_UNLOCK_ALL,
            'video_id' => $videoId,
            'status' => 1,
            ['refund_status', 'in', [PayRecord::REFUND_STATUS_DEFAULT,PayRecord::REFUND_STATUS_FAIL]]]
        );

        // 观看扣费记录
        $videoDetailIds = $this->getVideoPayLog($videoId, $uid);

        //会员判断
        $userData = $this->userModel->getInfoById($uid, 'id,is_members,expiration_time,money');
        $is_member = 0;
        if ($userData && $userData['is_members'] == 1 && $userData['expiration_time'] > time()) {
            $payRecords = $this->payRecordModel
                ->field('id,order_no,type,video_id,total_fee,activation_time,pay_time,refund_status')
                ->where(['uid' => $uid, 'status' => 1])
                ->where('refund_status','<>', PayRecord::REFUND_STATUS_SUCC)
                ->whereIn('type',[2,3,4,5,6,7,8,11,15])
                ->select()->toArray();

            $is_free = app(VideoService::class)->memberMatchFree($payRecords, $videoId);
            $is_member = $is_free ? 1 : 0;
        }

        $data['is_member'] = $is_member;
        $data['user_money'] = $userData ? $userData['money'] : 0;

        $this->redis->select(7);
        $data['collect'] = $this->getVideoAllDetail($videoId,$playPlatform,$videoData['original_id']);
        foreach ($data['collect'] as &$datum) {
            $originIsPay = $datum['is_pay'];
            $originPayAmount = $datum['pay_amount'];
            if ($tempConf == 'mount' && !empty($mountFixedChargeData)) {    //挂载
                $datum['is_pay'] = 1;
                $datum['pay_amount'] = $mountFixedChargeData['pay_amount'];
                if (empty($mountFixedChargeData['is_new_version'])) { //老版挂载
                    if ($mountFixedChargeData['sort'] > $datum['sort']) {
                        $datum['is_pay'] = 0;
                        $datum['pay_amount'] = 0;
                    }
                } else {    //新版挂载
                    if ($mountFixedChargeData['charge_type'] == 1) {    //固定收费
                        if ($mountFixedChargeData['sort'] > $datum['sort']) {
                            $datum['is_pay'] = 0;
                            $datum['pay_amount'] = 0;
                        }
                    } elseif ($mountFixedChargeData['charge_type'] == 2 && !empty($intervalChargeData)) {    //区间收费
                        $intervalConf = $customChargeService->handleIntervalRecharge($intervalChargeData, $datum['sort'],$originIsPay, $originPayAmount);
                        if($intervalConf){
                            $datum['is_pay'] = $intervalConf['is_pay'];
                            $datum['pay_amount'] = $intervalConf['pay_amount'];
                        }
                    }
                }
            } elseif ($tempConf == 'link' && !empty($fixedChargeData) && !empty($newRechargeConf)) {    //链接
                if ($newRechargeConf == 2 && !empty($intervalChargeData)) {
                    $intervalConf = $customChargeService->handleIntervalRecharge($intervalChargeData, $datum['sort'],$originIsPay, $originPayAmount);
                    if($intervalConf){
                        $datum['is_pay'] = $intervalConf['is_pay'];
                        $datum['pay_amount'] = $intervalConf['pay_amount'];
                    }
                } else {
                    $datum['is_pay'] = 1;
                    $datum['pay_amount'] = $fixedChargeData['pay_amount'];
                    if ($fixedChargeData['sort'] > $datum['sort']) {
                        $datum['is_pay'] = 0;
                        $datum['pay_amount'] = 0;
                    }
                }
            }
            $datum['is_free'] = $datum['is_pay'];
            // 解锁全解和已观看不收费
            if ($datum['is_pay'] == 1 && (in_array($datum['id'], $videoDetailIds) || count($unlockAll))) {
                $datum['is_pay'] = 0;
                $datum['pay_amount'] = 0;
            }
            // 是否会员
            if ($datum['is_pay'] == 1 && $is_member == 1) {
                $datum['is_pay'] = 0;
                $datum['pay_amount'] = 0;
            }

            $datum['pay_amount'] = (int)$datum['pay_amount'];
        }

        //加密数据
        $encryptData = $this->wechatEncryptData($data['collect'], $uid, $videoData['drama_id']);
        if ($encryptData) {
            $data['free_list'] = $encryptData['freeList'];
            $data['encryptStr'] = $encryptData['encrypt'];
        }

        return $data;
    }

    //微信加密
    public function wechatEncryptData(array $data, $uid, $drama_id): array
    {
        $free_list = [];
        $charge_list = [];
        $freeMax = 0;
        foreach ($data as $item) {
            if ($item['is_pay'] == 1) {
                $count = count($charge_list);
                if ($count == 0) {
                    $charge_list[0][] = $item['sort'];
                } else {
                    $end = $charge_list[$count-1];
                    if ((max($end) + 1) == $item['sort']) {
                        $charge_list[$count-1][] = $item['sort'];
                    } else {
                        $charge_list[$count][] = $item['sort'];
                    }
                }
            } else {
                $count = count($free_list);
                if ($count == 0) {
                    $free_list[0][] = $item['sort'];
                    if ($item['is_free'] == 0) {
                        $freeMax = $item['sort'];
                    }
                } else {
                    if ($count == 1 && $item['is_free'] == 0) {
                        $freeMax = $item['sort'];
                    }
                    $end = $free_list[$count-1];
                    if ((max($end) + 1) == $item['sort']) {
                        $free_list[$count-1][] = $item['sort'];
                    } else {
                        $free_list[$count][] = $item['sort'];
                    }
                }
            }
        }

        $serial_list = [];
        //免费剧集
        foreach ($free_list as $free) {
            $serial_list[] = [
                "start_serial_no" => min($free),
                "end_serial_no" => max($free),
                "status" => 1
            ];
        }
        //免费剧第一项
        $freeList = $serial_list ? $serial_list[0] : [];
        if (!empty($freeList)) {
            $freeList['end_serial_no'] = $freeMax;
        }

        //收费剧集
        foreach ($charge_list as $charge) {
            $serial_list[] = [
                "start_serial_no" => min($charge),
                "end_serial_no" => max($charge),
                "status" => 2
            ];
        }

        $result['freeList'] = $freeList;
        $result['encrypt'] = WechatService::encryptPlayData($uid, $drama_id, $serial_list);
        return $result;
    }

    /**
     * 获取首页分类视频数据
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param array params
     * @param int type 1排行 2最新 3热门
     * @return array
    */
    public function getHomeTypeData(array $params, int $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 30;

        $condition = [];
        $order = '';
        $appId = $params['app_id'] ?? 1;
        $playPlatform = $params['play_platform'] ?? 1;
	//增加判断当前链接是否属于分销商
        $is_automatic= $this->getIsAutomatic($uid);
        $redis = Cache::store('redis')->handler();
        //新加一个判断是否为广告链接进入，如果是就不限制，不是就限制
        //新加 start
        $redis->select(7);
        $linkidstatus=$redis->get('link_id_status'.$uid.'-'.$appId);
        if(empty($linkidstatus)||$linkidstatus==0){
            $app=$this->applet->getInfoById($appId,'vt_id');
            if(!empty($app['vt_id'])) {
                $vtempte = $this->videoTemplateModel->getInfoById($app['vt_id'], '*');
                if(!empty($vtempte['video_arr'])) {
                    $condition[] = ['id','', $vtempte['video_arr']];
                }
            }
        }
        //新加 end 
 
    
        switch ($params['type']) {
            case 1:
                // 排行
                $key = config('redis_key.api_video_ranking_list').$is_automatic.$page.$appId;
                if($playPlatform == 1){ // 微信小程序
                    $key = config('redis_key.api_video_ranking_list').$is_automatic.$page.$appId;
                }else if($playPlatform == 2) { // 抖音小程序
                    $key = config('redis_key.tiktok_api_video_ranking_list').$is_automatic.$page.$appId;
                }
                $data = $redis->get($key);
                if (empty($data)) {
                    //$where = ['is_delete' => 0, 'is_shelves' => 1];
                    // by add huangxiaoshan 2023-07-24 新增根据播放平台过滤数据.
                    // $condition = [];
                    $condition[] = ['play_platform','find in set',$playPlatform];
                    $condition[] = ['is_delete','=',0];
                    $condition[] = ['is_shelves','=',1];
                    $order = 'total_consume desc, frequency desc, give_count desc';
                    //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
                    //自投appid,展示自投剧
                      //增加一个判断当前链接是否是分销商
                      if($is_automatic != 2){
                        $condition[] = ['is_copy','=',(int)$is_automatic];
                    }else{
                        if(in_array($appId, config('enum.my_appid'))){
                            $condition[] = ['is_copy','=',0];
                        }else{
                            $condition[] = ['is_copy','=',1];
                        }
                    }
                  
                    //end
                    //$data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name, cover_img, label, give_count, title_label', $order);
                    $data = $this->videosModel->getPagingDataByWhere($condition, $page, $limit, 'id, name, cover_img, label, give_count, title_label,original_id,sylloge,drama_id', $order);
                    //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
                    //不是自投appid,展示复制剧
                    if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1){
                        foreach($data['data'] as $k_d =>$v_d){
                            $original = $this->videosModel->getInfoById($data['data'][$k_d]['original_id']); 
                            if(!empty($original)){
                                $data['data'][$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                            }
                        }
                    }
                    //end
                    $redis->set($key, json_encode($data), 86400);
                } else {
                    $data = json_decode($data, true);
                }
                break;
            case 2:
                // 最新
                $key = config('redis_key.api_video_new_list').$is_automatic.$page.$appId;
                if($playPlatform == 1){ // 微信小程序.
                    $key = config('redis_key.api_video_new_list').$is_automatic.$page.$appId;
                }else if($playPlatform == 2) { // 抖音小程序
                    $key = config('redis_key.tiktok_api_video_new_list').$is_automatic.$page.$appId;
                }

                $data = $redis->get($key);
                if (empty($data)) {
                    // by add huangxiaoshan 2023-07-24 新增根据播放平台过滤数据.
                    //$where = ['is_delete' => 0, 'is_shelves' => 1, 'type' => 1];
                    // $condition = [];
                    $condition[] = ['play_platform','find in set',$playPlatform];
                    $condition[] = ['is_delete','=',0];
                    $condition[] = ['is_shelves','=',1];
                    $condition[] = ['type','=',1];
                    $order = 'id desc, frequency desc, give_count desc';
                    //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
                    //自投appid,展示自投剧
                    //增加一个判断当前链接是否是分销商
                    if($is_automatic != 2){
                        $condition[] = ['is_copy','=',(int)$is_automatic];
                    }else{
                        if(in_array($appId, config('enum.my_appid'))){
                            $condition[] = ['is_copy','=',0];
                        }else{
                            $condition[] = ['is_copy','=',1];
                        }
                    }
                    //end
                    //$data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name, cover_img, label, give_count, title_label', $order);
                    $data = $this->videosModel->getPagingDataByWhere($condition, $page, $limit, 'id, name, cover_img, label, give_count, title_label,original_id,sylloge,drama_id', $order);
                    //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
                    //不是自投appid,展示复制剧
                    if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1){
                        foreach($data['data'] as $k_d =>$v_d){
                            $original = $this->videosModel->getInfoById($data['data'][$k_d]['original_id']); 
                            if(!empty($original)){
                                $data['data'][$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                            }
                        }
                    }
                    // end
                    $redis->set($key, json_encode($data), 86400);
                } else {
                    $data = json_decode($data, true);
                }
                break;
            case 3:
                // 热门
                $key = config('redis_key.api_video_hot_list').$is_automatic.$page.$appId;
                if($playPlatform == 1){ // 微信小程序.
                    $key = config('redis_key.api_video_hot_list').$is_automatic.$page.$appId;
                }else if($playPlatform == 2) { // 抖音小程序
                    $key = config('redis_key.tiktok_api_video_hot_list').$is_automatic.$page.$appId;
                }

                $data = $redis->get($key);
                if (empty($data)) {
                    // by add huangxiaoshan 2023-07-24 新增根据播放平台过滤数据.
                    //$where = ['is_delete' => 0, 'type' => 2, 'is_shelves' => 1];
                    // $condition = [];
                    $condition[] = ['play_platform','find in set',$playPlatform];
                    $condition[] = ['is_delete','=',0];
                    $condition[] = ['is_shelves','=',1];
                    $condition[] = ['type','=',2];
                    $order = 'total_consume desc, frequency desc, give_count desc';
                    //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
                    //自投appid,展示自投剧
                    
                     //增加一个判断当前链接是否是分销商
                     if($is_automatic != 2){
                        $condition[] = ['is_copy','=',(int)$is_automatic];
                    }else{
                        if(in_array($appId, config('enum.my_appid'))){
                            $condition[] = ['is_copy','=',0];
                        }else{
                            $condition[] = ['is_copy','=',1];
                        }
                    }
                    //end
                    //$data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name, cover_img, label, give_count, title_label', $order);
                    $data = $this->videosModel->getPagingDataByWhere($condition, $page, $limit, 'id, name, cover_img, label, give_count, title_label,original_id,sylloge,drama_id', $order);
                    //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
                    //不是自投appid,展示复制剧
                    if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1){
                        foreach($data['data'] as $k_d =>$v_d){
                            $original = $this->videosModel->getInfoById($data['data'][$k_d]['original_id']); 
                            if(!empty($original)){
                                $data['data'][$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                            }
                        }
                    }
                    // end
                    $redis->set($key, json_encode($data), 86400);
                } else {
                    $data = json_decode($data, true);
                }
                break;
            case 4: //免费专区
                $applet = $this->applet->getInfoByWhere(['app_id' => $appId], 'name,is_open_ad');
                $isOpenAd = $applet ? $applet['is_open_ad'] : 0;
                if (!$isOpenAd) {
                    return [];
                }
                $key = config('redis_key.api_video_free_list').$is_automatic.$page.$appId;
                if($playPlatform == 1){ // 微信小程序.
                    $key = config('redis_key.api_video_free_list').$is_automatic.$page.$appId;
                } else if($playPlatform == 2) { // 抖音小程序
                    $key = config('redis_key.tiktok_api_video_free_list').$is_automatic.$page.$appId;
                }
                $data = $redis->get($key);
                if (empty($data)) {
                    $condition = [];
                    $condition[] = ['play_platform','find in set',$playPlatform];
                    $condition[] = ['is_delete','=',0];
                    $condition[] = ['is_shelves','=',1];
                    $condition[] = ['type','=',3];

                    //增加一个判断当前链接是否是分销商
                    if($is_automatic != 2){
                        $condition[] = ['is_copy','=',(int)$is_automatic];
                    }else{
                        if(in_array($appId, config('enum.my_appid'))){
                            $condition[] = ['is_copy','=',0];
                        }else{
                            $condition[] = ['is_copy','=',1];
                        }
                    }

                    $order = 'id desc';
                    $data = $this->videosModel->getPagingDataByWhere($condition, $page, $limit, 'id, name, cover_img, label, give_count, title_label, original_id, sylloge,drama_id', $order);

                    //不是自投appid,展示复制剧
                    if(!in_array($appId, config('enum.my_appid')) || $is_automatic == 1) {
                        foreach($data['data'] as $k_d =>$v_d){
                            if (empty($v_d['original_id'])) {
                                continue;
                            }
                            $original = $this->videosModel->getInfoById($v_d['original_id']);
                            if(!empty($original)){
                                $data['data'][$k_d]['name']=$original['name'];//用原始剧的名称替换复制剧的名称
                            }
                        }
                    }
                    // end
                    $redis->set($key, json_encode($data), 86400);
                } else {
                    $data = json_decode($data, true);
                }
                break;
            default:
                return [];
        }

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');
            // $watchData = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_detail_id, video_id');
            // $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $videoDetailIds = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $videoDetailIds = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($videoDetailIds), config('redis_key.user_watch_record_expire'));
            }

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['video_detail_id'] = empty($videoDetailIds[$item['id']]) ? 0 : $videoDetailIds[$item['id']];
            }
        }

        return $data;
    }
    /**
     * 判断是否为分销商推广链接
     *
     * @param [type] $uid  用户id
     * @return int
     */
    public function getIsAutomatic($uid){
        $linkIdKey = config('redis_key.api.user_login');
        $this->redis->select(8);
        $linkId=json_decode($this->redis->get($linkIdKey . $uid),true);
        if (!empty($linkId['link_id'])) {
            $linklist=$this->linkModel->getInfoByWhere(['id'=>$linkId['link_id']],'responsibility_person_id');
            if (!empty($linklist)) {
                $responsibility = $this->responsibilityPersonModel->getInfoByWhere(['id' => $linklist['responsibility_person_id']], 'company_id');
                if(!empty($responsibility)) {
                    $data = $this->companyModel->getInfoById($responsibility['company_id'], 'is_distributor');
                    return isset($data['is_distributor']) ? (int)$data['is_distributor'] : 2;
                }
            }
        }
        return 2;
    }
}